//useLoadQuestionData
import { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import { getQuestionService } from '../services/question'
import { useRequest } from 'ahooks'
import { useDispatch } from 'react-redux'
import { resetComponents } from '../store/componetnsReducer/index'
import { resetPageInfo } from '../store/pageInfoReducer'
function useLoadQuestionData() {
  const dispatch = useDispatch()
  const { id = '' } = useParams()
  const { data, loading, error, run } = useRequest(
    async (id: string) => {
      if (!id) throw Error('没有文件ID')
      const data = await getQuestionService(id)
      return data
    },
    {
      manual: true,
    }
  )
  // 根据获取的data设置redux store
  useEffect(() => {
    if (!data) return
    const { title = '', componetnList = [],desc='',js='',css='',isPublished=false } = data
    let selectedId:string=''
    if(componetnList.length){
      selectedId=componetnList[0].fe_id
    }
    //把componentList 存储到 Readux store中
    dispatch(resetComponents({ componetnList, selectedId,copiedComponent:null}))
    //把pageInfo 存储到 redux store中
    dispatch(resetPageInfo({title,desc,js,css,isPublished}))

  }, [data])
  useEffect(() => {
    run(id)
  }, [id])
  return { loading, error }
}
export default useLoadQuestionData
